<template>
    <div
        v-if="isShowPopover"
        @mouseleave="onClose"
        :style="[popoverCssObj]"
        class="popover-main"
    >
        <div class="popover-content">
            <a-button
                v-for="(item, index) in pyList"
                :key="index"
                type="dashed"
                shape="circle"
                style="margin-right: 10px"
                @click="handleItemClick(item)"
            >
                {{ item.label }}
            </a-button>
        </div>
    </div>
</template>
<script setup>
import { ref, watch, onUnmounted } from "vue";
import { getEmitter } from "../../coreComponents/emitter.js";
import { handleReplacePinYinNode } from "../../coreComponents/helper.js";

const pyList = ref([]);
const editorRef = ref();
const isShowPopover = ref(false);
const popoverCssObj = ref({});
const nodeObj = ref()
const onOpen = (editor) => {
    if (!editorRef.value && editor) {
        // console.log('onOpen')
        editorRef.value = editor;
        handleEditorCreated();
    }
};

onUnmounted(() => {
    getEmitter(editorRef.value)?.off(
        "ssml-remark-click",
        handleSSMLRemarkClick
    );
});

function onClose() {
    isShowPopover.value = false;
}

function handleEditorCreated() {
    getEmitter(editorRef.value).off("ssml-remark-click", handleSSMLRemarkClick);
    getEmitter(editorRef.value).on("ssml-remark-click", handleSSMLRemarkClick);
}

function handleSSMLRemarkClick(editor, elem) {
    if (elem.type === "ssml-mark") {
        console.log("handleSSMLRemarkClick");
        var obj = editor.getNodePosition(elem);
        if (obj.top) {
            obj.marginTop = "-40px";
            obj.paddingTop = "-40px";
        } else {
            obj.marginBottom = "-40px";
            obj.paddingBottom = "40px";
        }
        pyList.value = elem.ph;
        nodeObj.value = elem
        popoverCssObj.value = obj;
        isShowPopover.value = true;
    }
}

function handleItemClick(item){
    onClose()
    handleReplacePinYinNode(editorRef.value, nodeObj.value, item)
}

const props = defineProps({
    editor: {
        type: Object,
        default: null,
    },
});

watch(
    () => props.editor,
    (val) => {
        // console.log("props.editor", props.editor);
        onOpen(props.editor);
    },
    { immediate: true, deep: true }
);

// 调用这个函数将子组件的一些数据和方法暴露出去
defineExpose({
    onOpen,
});
</script>

<style>
.popover-main {
    position: absolute;
    z-index: 1000;
}

.popover-content {
    background-color: #fff;
    border: 1px solid #ccc;
    padding: 10px;
    border-radius: 5px;
    user-select: none;
    position: relative;
}
.popover-content::before {
    content: "";
    position: absolute;
    bottom: 100%;
    left: 20%;
    border-width: 5px; /* 可以根据需要调整大小 */
    border-style: solid;
    border-color: transparent;
    border-bottom-color: #ccc; /* 边框颜色 */
    transform: translateX(-50%);
}
</style>
